#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include "system.h"
#include "f1c100s_de.h"
#include "f1c100s_timer.h"
#include "f1c100s_intc.h"
#include "f1c100s_gpio.h"
#include "f1c100s_pwm.h"
#include "f1c100s_uart.h"
#include "f1c100s_dma.h"
#include "arm32.h"
#include "disp.h"

volatile uint32_t step = 0;

void timer_irq_handler(void)
{
    ++step;
    tim_clear_irq(TIM0);
}

int main(void)
{
    system_init();            // Initialize clocks, mmu, cache, uart, ...
    arm32_interrupt_enable(); // Enable interrupts
    printf("\r\napp [display] run. compiled_time %s %s\r\n", __DATE__, __TIME__);
    disp_rgb_init();

    // 用timer 0作为计时器
    tim_init(TIM0, TIM_MODE_CONT, TIM_SRC_HOSC, TIM_PSC_1);
    tim_set_period(TIM0, 24000000UL / 1000UL); //1ms
    tim_int_enable(TIM0);
    intc_set_irq_handler(IRQ_TIMER0, timer_irq_handler);
    intc_enable_irq(IRQ_TIMER0);
    tim_start(TIM0);

    uint32_t colorCount = 7, index = 0;
    uint16_t colorList[] = {COLOR565_BLUE, COLOR565_GREEN, COLOR565_RED, COLOR565_YELLOW, COLOR565_WHITE, COLOR565_ORANGE, COLOR565_PURPLE};
    uint16_t testCount = 1000;

    // 一定要打开下面2句
    lcdSetWindows(0, 0, LCD_WIDTH, LCD_HIGHT);
    // de_lcd_8080_auto_mode(true);
    lcdDirectFlush(true);

    uint16_t rectX, rectY, rectWidth, rectHeight;

    for(index = 0; index < testCount; ++index)
    {
        rectX = rand() % (LCD_WIDTH >> 1);
        rectY = rand() % (LCD_HIGHT >> 1);
        
        rectWidth = rand() % LCD_WIDTH;
        if(rectX + rectWidth >= LCD_WIDTH)
        {
            rectWidth = LCD_WIDTH - rectX - 1;
        }

        rectHeight = rand() % LCD_HIGHT;
        if(rectY + rectHeight >= LCD_HIGHT)
        {
            rectHeight = LCD_HIGHT - rectY - 1;
        }

        disp_fill(rectX, rectY, rectWidth, rectHeight, colorList[index % colorCount]);

        delay_soft(1); // 1 * 7 = 7ms
    }

    tim_stop(TIM0);

    float interval = testCount / (step / 1000.0f);
    printf("time interval: %ldms, fps: %ld.\n", step, (uint32_t)interval);

    disp_clear(0);

    while(true)
    {
        delay_soft(150); // 150 * 7 = 1050ms
    }

    return 0;
}
